<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="default"
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" sortable />
      <el-table-column label="会员名称" align="center" prop="name" />
      <el-table-column label="有效期" align="center" prop="period">
        <template slot-scope="scope">
          <span>{{ scope.row.period === 0 ? '永久有效' : scope.row.periodDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="换脸次数" align="center" prop="changeFaceCount" />
      <el-table-column label="设为选中" align="center" prop="setChoose">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.setChoose" active-color="#00E266" @change="handleSwitchChangeSet(scope.row)" v-if="scope.row.type === 2"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="show">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.show" active-color="#00E266" @change="handleSwitchChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price">
        <template slot-scope="scope">
          <span>{{ scope.row.price ? `￥${scope.row.price}` : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="oldPrice">
        <template slot-scope="scope">
          <span>{{ scope.row.oldPrice ? `￥${scope.row.oldPrice}` : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="任务内容" align="center" prop="taskContent">
        <template slot-scope="scope">
          <span>{{ getTaskContent(scope.row.taskContent) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
              size="mini"
              type="text"
              style="color: #f00"
              v-if="scope.row.type === 2"
              @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改会员管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="会员名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入会员名称" :disabled="comboName === '图片单次收费'" />
        </el-form-item>
        <el-form-item label="原价：" prop="oldPrice" v-if="comboName !== '图片单次收费'">
          <el-input v-model="form.oldPrice" placeholder="请输入原价">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="价格：" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="comboName !== '图片单次收费' ? '是否显示' : '显示状态'" prop="show">
          <el-switch v-model="form.show" active-color="#00E266"></el-switch>
        </el-form-item>
        <el-form-item label="排序：" prop="orderNum" v-if="comboName !== '图片单次收费'">
          <el-input-number v-model="form.orderNum" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="有效期：" prop="period" v-if="comboName !== '图片单次收费'">
          <el-radio-group v-model="form.period">
            <el-radio :label="1">期限</el-radio>
            <el-radio :label="0">永久</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.period === 1 && comboName !== '图片单次收费'">
          <el-row>
            <el-col :span="4">
              <el-input v-model="form.periodValue" placeholder="请输入" @input="handleInput" />
            </el-col>
            <el-col :span="5" :offset="1">
              <el-select v-model="form.periodUnit" placeholder="请选择">
                <el-option
                    v-for="item in unitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="换脸限制：" v-if="comboName !== '图片单次收费'">
          <el-row>
            <el-col :span="4">
              <el-select v-model="form.receiveUnit" placeholder="请选择">
                <el-option
                    v-for="item in receiveUnitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5" :offset="1" v-if="form.receiveUnit">
              <el-input v-model="form.receiveCount">
                <template slot="append">{{ form.receiveUnit === 1 ? '次' : '分钟' }}</template>
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--编辑体验会员-->
    <el-dialog title="编辑" :visible.sync="experienceOpen" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="experienceForm" :model="experienceForm" :rules="rules" label-width="100px">
        <el-form-item label="会员名称：" prop="name">
          <el-input v-model="experienceForm.name" placeholder="请输入会员名称" />
        </el-form-item>
        <el-form-item label="是否显示" prop="show">
          <el-switch v-model="experienceForm.show" active-color="#00E266"></el-switch>
        </el-form-item>
        <el-form-item label="排序：" prop="orderNum">
          <el-input-number v-model="experienceForm.orderNum" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="有效期：">
          <el-row>
            <el-col :span="3">
              <el-input v-model="experienceForm.periodValue" placeholder="请输入" @input="handleInput" />
            </el-col>
            <el-col :span="3" :offset="1">
              <el-select v-model="experienceForm.periodUnit" placeholder="请选择">
                <el-option
                    v-for="item in unitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="任务内容：" prop="taskContent">
          <el-button type="primary" @click="addOpen = true">添加任务</el-button>
          <div style="display: flex;flex-wrap: wrap;align-items: center;">
            <div v-for="(item, index) in taskList" :key="index"
                 style="position: relative;border: 1px solid #bfcbd9;border-radius: 5px;padding: 0 20px;margin-top: 10px;margin-right: 20px">
              <span>{{ item.taskName }}({{ item.completeCount }}次)</span>
              <span style="color: #ff0000;position: absolute;top: -8px;right: -8px;border: 1px solid #ff0000;border-radius: 7px;font-size: 12px;line-height: 15px;width: 15px;text-align: center;cursor: pointer;" @click="handleTaskDelete(index)">X</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="领取次数：" prop="receiveCount">
          <el-input-number v-model="experienceForm.receiveCount" />
        </el-form-item>
        <el-form-item label="换脸次数：" prop="receiveCount">
          <el-input-number v-model="experienceForm.experienceChangeFace" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExperienceForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--添加任务弹窗-->
    <el-dialog title="添加任务" :visible.sync="addOpen" width="40%" append-to-body :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="140px">
        <el-form-item label="选择任务：" prop="taskId">
          <el-select v-model="addForm.taskId" style="width: 100%">
            <el-option
              v-for="item in taskData"
              :key="item.id"
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="完成所需次数：" prop="completeCount">
          <el-input-number :min="0" v-model="addForm.completeCount"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleTaskAdd">确 定</el-button>
        <el-button @click="addCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 视频单次收费/图片单次收费 -->
    <el-dialog :title="'编辑'+comboName" :visible.sync="chargeOpen" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="addForm" :model="chargeForm" label-width="120px">
        <el-form-item label="会员名称" prop="memberName">
          <el-input v-model="chargeForm.memberName" disabled />
        </el-form-item>
        <el-form-item label="价格：" prop="singlePriceParams">
          <el-row v-for="(row, index) in forntChargeParams" style="margin-bottom: 10px">
            <el-col :span="4">
              <el-input-number controls-position="right" style="width: 100%" v-model="row.minSecond"></el-input-number>
            </el-col>
            <el-col :span="1" style="text-align: center;">-</el-col>
            <el-col :span="4">
              <el-input-number controls-position="right" style="width: 100%" v-model="row.maxSecond"></el-input-number>
            </el-col>
            <el-col :span="3" style="text-align: center;">秒，收费</el-col>
            <el-col :span="4">
              <el-input-number controls-position="right" style="width: 100%" v-model="row.price"></el-input-number>
            </el-col>
            <el-col :span="1" style="text-align: center;">元</el-col>
            <el-col :span="2" v-if="index !== 0">
              <i class="el-icon-close" @click="handleChargeDelete(index)"></i>
            </el-col>
          </el-row>
          <el-button class="mt-10" style="margin: 10px 0;" type="primary" icon="el-icon-plus" @click="handleAddChargeItem"></el-button>
          <el-row>
            <el-col :span="4">
              <el-input-number controls-position="right" style="width: 100%" v-model="lastChargeForm.minSecond"></el-input-number>
            </el-col>
            <el-col :span="4" style="text-align: center;">秒以上，每增加</el-col>
            <el-col :span="4">
              <el-input-number controls-position="right" style="width: 100%" v-model="lastChargeForm.addEverySecond"></el-input-number>
            </el-col>
            <el-col :span="4" style="text-align: center;">秒，收费增加</el-col>
            <el-col :span="4">
              <el-input-number controls-position="right" style="width: 100%" v-model="lastChargeForm.price"></el-input-number>
            </el-col>
            <el-col :span="1" style="text-align: center;">元</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="显示状态：" prop="memberShow">
          <el-switch v-model="chargeForm.memberShow"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleChargeEdit">确 定</el-button>
        <el-button @click="chargeOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMemberList, saveMemberInfo, removeMemberInfo, getTaskList, saveExperienceMemberInfo, setMemberInfo, getVideoChargeDetail, saveVideoCharge } from "@/api/shuiyin/shuiyin";

export default {
  name: "Combo",
  data() {
    return {
      // 有效期单位数据
      unitOptions: [
        {
          value: 1,
          label: '天'
        }, {
          value: 2,
          label: '月'
        }, {
          value: 3,
          label: '年'
        }
      ],
      // 换脸单位
      receiveUnitOptions: [
        {
          value: 1,
          label: '按次数'
        },
        // {
        //   value: 2,
        //   label: '按时间'
        // }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户管理表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "会员名称不能为空", trigger: "blur" }
        ],
      },
      // 会员类型，1 体验会员   2 正常会员
      memberType: 1,
      // 体验会员弹出层
      experienceOpen: false,
      // 体验会员表单
      experienceForm: {},
      // 体验会员添加的任务列表
      taskList: [],
      // 添加任务弹出层
      addOpen: false,
      addForm: {
        taskId: null,
        taskName: null,
        completeCount: 0
      },
      taskData: [],
      addRules: {
        taskId: [
          { required: true, message: "请选择任务", trigger: "change" }
        ],
        completeCount: [
          { required: true, message: "完成所需次数不能为空", trigger: "blur" }
        ]
      },
      comboName: '', // 会员名称
      chargeForm: {}, // 收费表单
      chargeOpen: false,
      lastChargeForm: {},
      forntChargeParams: []
    };
  },
  created() {
    this.getList();
    this.getTask();
  },
  methods: {
    /** 查询租户管理列表 */
    getList() {
      this.loading = true;
      getMemberList(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleInput(event) {
      console.log(event);
      this.$forceUpdate()
    },
    getTask() {
      getTaskList().then(response => {
        this.taskData = response.data;
      })
    },
    // 取消按钮
    cancel() {
      console.log(this.memberType)
      if (this.memberType === 2 || this.memberType === 3) {
        this.open = false;
      } else {
        this.experienceOpen = false;
      }
      this.reset();
    },
    // 添加任务取消
    addCancel() {
      this.addOpen = false;
      this.addForm = {
        taskId: null,
        completeCount: 0
      }
    },
    // 添加任务确定
    handleTaskAdd() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          this.taskList.push({
            taskId: this.addForm.taskId,
            taskName: this.getTaskName(this.addForm.taskId),
            completeCount: this.addForm.completeCount
          })
          this.addOpen = false;
        }
      })
    },
    getTaskName(id) {
      for(let i=0;i<this.taskData.length; i++) {
        if (this.taskData[i].id === id) {
          return this.taskData[i].name;
        }
      }
    },
    getTaskContent(str) {
      if (!str) return
      const array = JSON.parse(str);
      let newArray = [];
      array.forEach(element => {
        newArray.push(`${element.taskName}(${element.completeCount === undefined ? 0: element.completeCount}次)`)
      })
      return newArray.join('  ')
    },
    handleTaskDelete(index) {
      this.taskList.splice(index, 1)
    },
    // 表单重置
    reset() {
      if (this.memberType === 2) {
        this.form = {
          id: null,
          name: null,
          oldPrice: null,
          orderNum: null,
          period: 1,
          periodUnit: 2,
          periodValue: null,
          price: null,
          show: false,
          receiveUnit: null,
          receiveCount: null,
          // setChoose: true
        };
        this.resetForm("form");
      } else {
        this.experienceForm = {
          id: null,
          name: null,
          period: 1,
          periodUnit: 2,
          periodValue: null,
          show: false,
          // setChoose: true,
          receiveCount: 0,
          taskContent: null,
          orderNum: null,
        };
        this.resetForm("experienceForm");
      }

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.memberType = 2;
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.memberType  = row.type;
      this.comboName = row.name;
      if (row.type === 2 || (row.type === 3 && this.comboName === '图片单次收费')) { // 正常会员
        this.reset();
        const id = row.id || this.ids
        this.form = JSON.parse(JSON.stringify(row));
        if (row.period !== 0) {
          this.form.period = 1;
          this.form.periodValue = row.period;
        }
        this.open = true;
        this.title = "修改";
      } else if (row.type === 3 && this.comboName === '视频单次收费') { // 视频单次收费/图片单次收费
          const { data } = await getVideoChargeDetail({memberId: row.id});
          this.chargeForm = data;
          this.lastChargeForm = data.singlePriceParams[data.singlePriceParams.length - 1]
          this.forntChargeParams = data.singlePriceParams.splice(0, data.singlePriceParams.length -1)
          this.chargeForm = data;
          this.chargeOpen = true;
      } else {
        this.reset();
        const id = row.id || this.ids
        this.experienceForm = JSON.parse(JSON.stringify(row));
        if (row.period !== 0) {
          this.experienceForm.period = 1;
          this.experienceForm.periodValue = row.period;
        }
        this.taskList = this.experienceForm.taskContent ? JSON.parse(this.experienceForm.taskContent) : [];
        this.taskList.forEach(element => {
          if (element.completeCount === undefined) {
            element.completeCount = 0
          }
        })
        this.experienceOpen = true;
      }
    },
    handleAddChargeItem() {
      this.forntChargeParams.push({
        // id: '',
        minSecond: 0,
        maxSecond: 0,
        price: 0,
        addEverySecond: null,
        orderNum: this.forntChargeParams[this.forntChargeParams.length -1].orderNum + 1,
        memberId: this.chargeForm.memberId
      })
    },
    handleChargeDelete(index) {
      this.forntChargeParams.splice(index, 1)
    },
    handleChargeEdit() {
      this.lastChargeForm.maxSecond = 0
      this.chargeForm.singlePriceParams = JSON.stringify([...this.forntChargeParams, ...[this.lastChargeForm]]);
      saveVideoCharge(this.chargeForm).then(res => {
        this.$modal.msgSuccess("修改成功");
        this.chargeOpen = false;
        this.getList();
      })
    },
    handleSwitchChange(row) {
      let obj = JSON.parse(JSON.stringify(row));
      // if (row.period === 1) {
      //   obj.period = obj.periodValue;
      // }
      saveMemberInfo(obj).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    /** 设为选中 */
    handleSwitchChangeSet(row) {
      setMemberInfo(row.id).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let obj = JSON.parse(JSON.stringify(this.form));
            if (this.form.period === 1) {
              obj.period = obj.periodValue;
            }
            saveMemberInfo(obj).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let obj = JSON.parse(JSON.stringify(this.form));
            if (this.form.period === 1) {
              obj.period = obj.periodValue;
            }
            saveMemberInfo(obj).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitExperienceForm() {
      this.$refs["experienceForm"].validate(valid => {
        if (valid) {
          this.experienceForm.taskContent = JSON.stringify(this.taskList);
          let obj = JSON.parse(JSON.stringify(this.experienceForm));
          if (this.experienceForm.period === 1) {
            obj.period = obj.periodValue;
          }
          saveExperienceMemberInfo(obj).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.experienceOpen = false;
            this.getList();
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const memberIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除会员管理编号为"' + memberIds + '"的数据项？').then(function() {
        return removeMemberInfo(memberIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
